/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.ui.widgets;

import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import com.aphrodite.image.ColorUtil;

//completed
//added touch screen support
/**
 * Button that can contain images also
 * <p>
 * <img src="../../../resources/aphro_btn.gif">
 * </p>
 * 
 * @author kentelt
 * 
 */
public final class Button extends TraversableWidget {

	private final class Ani extends TimerTask {
		public void run() {
			System.out.println("Button active threads " + Thread.activeCount());
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			reDrawWidget();
			// super.cancel();
			isPressed = false;
		}
	}

	private Image buttonImage;
	private String caption;
	private volatile boolean isPressed;
	// private ClickListener listener;

	// private int shadowColor = com.aphrodite.image.ColorUtil.adjustBrightness(
	// ColorUtil.covertToGrayscale(theme.bgColor), -40);

	private Timer timer;

	/**
	 * @param theme
	 *            to be used by the widget
	 * @param caption
	 *            of the button
	 */
	public Button(Theme theme, String caption) {
		super(theme, 0, 0);
		this.caption = caption;
		updateModel();
	}

	public void cleanUp() {
		buttonImage = null;
	}

	private void click() {

		if (!isPressed) {
			if (timer != null) {
				timer.cancel();
				timer = null;
			}
			isPressed = true;
			reDrawWidget();
			timer = new Timer();
			timer.schedule(new Ani(), 0);
			super.fire();
		}
	}

	public void fire() {
		click();
	}

	public boolean pointerPress(int px, int py) {
		/* if the click is within the bounds of the button */
		if (super.pointerPress(px, py)) {
			isPressed = true;
			reDrawWidget();
			return true;
		}
		return false;
	}

	public boolean pointerRelease(int x, int y) {
		/* if the click is within the bounds of the button */
		if (isVisible
				&& com.aphrodite.util.geom.GeomUtil.withinBounds(x, y, super.x, super.y, super.width, super.height)) {
			isPressed = false;
			reDrawWidget();
			super.fire();
			return true;
		}
		return false;

	}

	public void render(Graphics g) {
		if (!isVisible)
			return;
		int shadowClr = com.aphrodite.image.ColorUtil.adjustBrightness(ColorUtil.covertToGrayscale(theme.bgColor), -40);
		capture(g, width, height, true);
		g.setColor(isPressed ? shadowClr : 0xffffff);
		g.drawLine(0, 0, width, 0);// -- top line
		g.drawLine(0, 0, 0, height);// | left line

		int capX = (isPressed) ? 4 : 3;
		int capY = (isPressed) ? 4 : 3;

		if (buttonImage != null) {
			g.drawImage(buttonImage, capX, capY, 0);
			capX += buttonImage.getWidth() + 2;
			capY += buttonImage.getHeight() / 2 - (theme.widgetFont.getHeight() / 2);
		}
		/* button caption */
		g.setColor(theme.fgColor);
		if (caption != null) {
			if (theme.bmFont != null) {
				theme.bmFont.drawString(g, caption, capX, capY, 0);
			} else {
				g.setFont(theme.widgetFont);
				g.drawString(caption, capX, capY, 0);
			}
		}
		g.setColor(isPressed ? 0xffffff : shadowClr);
		g.drawLine(0, height, width, height);// __ bottom line
		g.drawLine(width, 0, width, height); // | right line
		/* border lines are not needed */
		release(g, width, height, false);

	}

	/**
	 * Set an image for the button.
	 * 
	 * <p>
	 * For now only the image can be set only to the left<br/> <img
	 * src="../../../resources/aphro_btn_Image.gif">
	 * </p>
	 * 
	 * @param image
	 */
	public void setImage(Image image) {
		this.buttonImage = image;
		updateModel();
		reDrawWidget();
		stateChanged(this);
	}

	public final void setText(String text) {
		this.caption = text;
		updateModel();
		reDrawWidget();
		stateChanged(this);
	}

	/**
	 * Overridden function. Button cannot have a title bar.
	 */
	public void setTitle(String title) {}

	protected final boolean traverse(final int dir, int viewportWidth, int viewportHeight, int[] visRect_inout) {
		if (dir == Canvas.DOWN || dir == Canvas.RIGHT) {
			if (location == UPPER) {
				System.out.println("Focus gained");
				location = IN;
			} else {
				location = LOWER;
				System.out.println("Focus lost");

				return false;
			}
		}
		// break;
		// case Canvas.UP:
		else if (dir == Canvas.UP || dir == Canvas.LEFT) {
			if (location == LOWER) {
				System.out.println("Focus gained");
				location = IN;
			} else {
				location = UPPER;
				System.out.println("Focus lost");
				return false;
			}
			// break;
		}
		return true;
	}

	protected final void updateModel() {
		int fontW = 0;
		int fontH = 0;
		if (caption != null) {
			if (theme.bmFont != null) {
				fontW = theme.bmFont.stringWidth(caption);
				fontH = theme.bmFont.getHeight();
			} else {
				fontW = theme.widgetFont.stringWidth(caption);
				fontH = theme.widgetFont.getHeight();
			}
		}
		width = 6 + fontW + (buttonImage != null ? buttonImage.getWidth() + (caption != null ? 2 : 0) : 0);
		height = 6 + Math.max((buttonImage != null ? buttonImage.getHeight() : 0), fontH);
		sizeChanged(width, height);
	}

}
